<template>
  <a-form
      :model="ruleForm"
      ref="ruleForm"
      v-bind="layout"
      :rules="rules"
      @finish="handleFinish"
  >
    <a-form-item label="学院名称" name="college_name">
      <a-input v-model:value="ruleForm.college_name" />
    </a-form-item>
    <a-form-item label="学院编号" name="college_num">
      <a-input v-model:value="ruleForm.college_num" />
    </a-form-item>
    <a-form-item label="学院责任人" name="college_principal">
      <a-select
        v-model:value="ruleForm.college_principal"
        style="width: 120px"
        ref="select"
      >
        <a-select-option
          v-for="item in college_principalSelectionOptions"
          :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="负责人电话" name="college_phone">
      <a-input v-model:value="ruleForm.college_phone" />
    </a-form-item>
    <a-form-item label="所属学校" name="school_name">
      <a-select
        v-model:value="ruleForm.school_name"
        style="width: 120px"
        ref="select"
      >
        <a-select-option
          v-for="item in school_nameSelectionOptions"
          :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import { message } from 'ant-design-vue'

export default {
  name: 'AddorEditInstituteInfo',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],
  data() {
    let validateCollegePrincipal = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择学院负责人");
      }
    };
    let validateSchoolName = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择学校名称");
      }
    };
    return {
      ruleForm: {
        college_name: '',
        college_num: '',
        college_principal: '',
        college_phone: '',
        school_name: '',
      },
      rules: {
        college_principal: [
          {
            validator: validateCollegePrincipal,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
        school_name: [
          {
            validator: validateSchoolName,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
      },
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      submitting: false,
      college_principalSelectionOptions: [],
      school_nameSelectionOptions: [],
      headers: {
        authorization: 'authorization-text',
      },
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {
       this.college_principalSelectionOptions = []
       this.school_nameSelectionOptions = []
      this.axios
        .get('/user_management/users')
        .then((res) => {
          const data = res.data
          for (let i = 0; i < data.length; ++i) {
            this.college_principalSelectionOptions.push({
              url: data[i].url,
              label: data[i].username,
            })
          }
        })
          this.axios
              .get('/unit_management/schools')
              .then((res) => {
                const data = res.data
                for (let i = 0; i < data.length; ++i) {
                  this.school_nameSelectionOptions.push({
                    url: data[i].url,
                    label: data[i].school_name,
                  })
                }
                this.ruleForm.school_name = data.length === 0 ? '' : data[0].url
                if (this.url !== '') {
                  this.axios
                      .get(this.url)
                      .then((res) => {
                        const data = res.data
                        this.ruleForm.college_name = data.college_name
                        this.ruleForm.college_num = data.college_num
                        this.ruleForm.college_principal = data.college_principal
                        this.ruleForm.college_phone = data.college_phone
                        this.ruleForm.school_name = data.school_name
                      })
                      .catch((error) => {
                        console.log('Error', error.message)
                      })
                }
              })
             .catch((error) => {
          console.log('Error', error.message)
          this.ruleForm.college_name = ''
        })
    },
    handleFinish(values) {
      this.submitting = true
      const formData = new FormData()
      formData.append('college_name', values.college_name)
      formData.append('college_num', values.college_num)
      formData.append('college_principal', values.college_principal)
      formData.append('college_phone', values.college_phone)
      formData.append('school_name', values.school_name)
      if (this.url !== '') {
        this.axios
          .put(this.url, formData)
          .then(() => {
            this.submitting = false
            message.success('修改成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('修改失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      } else {
        this.axios
          .post('/unit_management/colleges/', formData)
          .then(() => {
            this.submitting = false
            message.success('添加成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('添加失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      }
    },
  },
}
</script>
